<?php

namespace Game\Logic;

use \Common\Logic\BaseLogic;

/**
 * 用户logic
 */
class UserLogic extends BaseLogic
{

    private $userModel;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = D('User');
    }

    /**
     * 问题统计
     * @param array $where
     * @return mixed
     */
    public function statistics($where = array())
    {
        return $this->userModel->where($where)->count();
    }

    /**
     * 获取列表
     * @param int $page
     * @param int $size
     * @param $where
     * @return mixed
     */
    public function getList($page = 1, $size = 20, $where)
    {
        $list = $this->userModel->where($where)->page($page, $size)->order("id desc")->select();
        $total = $this->statistics($where);
        return static::$res->suc("成功", array(
            "list" => $list,
            "total" => $total
        ));
    }

    /**
     * 取一条数据
     * @param type $where
     * @return type
     */
    public function getInfo($where)
    {
        $info = $this->userModel->where($where)->find();
        return static::$res->suc("成功", $info);
    }


    /**
     * 编辑用户
     * @param $id
     * @param array $param
     * @return mixed
     */
    public function update($id, $param = array())
    {
        if (empty($id)) {
            return static::$res->err("id不能为空");
        }

        $where = array(
            "id" => $id
        );

        unset($param['id']);

        $userInfoRes = $this->getInfo($where);
        $userInfo = $userInfoRes['Result'];
        if (empty($userInfo)) {
            return static::$res->err("未找到用户");
        }

        if (empty($param)) {
            return static::$res->err("没有任何改变");
        }

        $count = $this->userModel->where($where)->save($param);
        if (empty($count)) {
            return static::$res->err("数据库异常，没有任何改变");
        }

        return static::$res->suc("操作成功");
    }

    /**
     * 更改用户已分成金额
     * @param $userId
     * @param $income
     * @return mixed
     */
    public function updataRecommIncome($userId, $income)
    {
        if (empty($userId)) {
            return static::$res->err("userId不能为空");
        }

        if (!(int)$income) {
            return static::$res->err("分成金额不能为空");
        }

        $where = array(
            "id" => $userId
        );

        $count = $this->userModel->where($where)->setInc('recomm_income', $income);
        if (empty($count)) {
            return static::$res->err("数据库异常，没有任何改变");
        }

        return static::$res->suc("操作成功");
    }
}
